﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using ProtoImaginer.Models;

namespace ProtoImaginer.ProtoPage
{
    public partial class SelectPage : PhoneApplicationPage
    {
        private PageListViewModel selectedPageItem;
        private Models.Control control;
        public SelectPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            DataContext = App.ViewModel;

            control = Models.ProtoDataContext.LoadControlByPK(NavigationContext.QueryString["controlId"]);
            var pageId = Models.ProtoDataContext.LoadImageByPK(control.ControlResidingImageId).PageId;
            var page = Models.ProtoDataContext.LoadPageByPK(pageId);
            App.ViewModel.LoadPages(page.ProjectId);

        }

        private void PageListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected index is -1 (no selection) do nothing
            if (PageListBox.SelectedIndex == -1)
                return;
            selectedPageItem = (sender as ListBox).SelectedItem as PageListViewModel;

            control.ControlLinkToImageId = Models.ProtoDataContext.LoadImagesByPageId(selectedPageItem.PageId).ImageId;
            
            Models.ProtoDataContext.SaveControl(control);
            NavigationService.GoBack();

            //var originPageId = Models.ProtoDataContext.LoadPageByPK(Models.ProtoDataContext.LoadImageByPK(control.ControlResidingImageId).PageId).PageId;
            //NavigationService.Navigate(new Uri("/ProtoPage/PageView.xaml?pageId=" + originPageId, UriKind.Relative));
        }
    }
}